package com.test.ftp;

import ftp.FtpBean;
import ftp.FtpListResult;
import ftp.FtpObserver;

public class FtpServerMain implements FtpObserver {

	FtpBean ftp;
	long num_of_bytes = 0;

	public FtpServerMain() {
		// Create a new FtpBean object.
		ftp = new FtpBean();
	}

	// Connect to a ftp server.
	public void connect() {
		try {
			ftp.ftpConnect("ftp.cs.cuhk.edu.hk", "anonymous",
					"citidancer@hongkong.com");
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	// Close connection
	public void close() {
		try {
			ftp.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	// Go to directory pub and list its content.
	public void listDirectory() {
		FtpListResult ftplrs = null;

		try {
			// Go to directory 'pub/redhat/redhat-6.2/i386/RedHat/RPMS'.
			ftp.setDirectory("pub/redhat/redhat-6.2/i386/RedHat/RPMS");
			// Get its directory content.
			ftplrs = ftp.getDirectoryContent();
		} catch (Exception e) {
			System.out.println(e);
		}

		// Print out the type and file name of each row.
		while (ftplrs.next()) {
			int type = ftplrs.getType();
			if (type == FtpListResult.DIRECTORY)
				System.out.print("DIR\t");
			else if (type == FtpListResult.FILE)
				System.out.print("FILE\t");
			else if (type == FtpListResult.LINK)
				System.out.print("LINK\t");
			else if (type == FtpListResult.OTHERS)
				System.out.print("OTHER\t");
			System.out.println(ftplrs.getName());
		}
	}

	// Get the file.
	public void getFile() {
		try {
			// Get the binary file 'kernel-2.2.14-5.0.i386.rpm' and save it to
			// the name 'local_file_name' in the hard disk.
			// Passing this class which implements the FtpObserver interface to
			// monitor this downloading progress. Every time new bytes are read,
			// the byteRead(int) method of this class is invoked by the bean.
			ftp.getBinaryFile("kernel-2.2.14-5.0.i386.rpm", "local_file_name",
					this);
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	// Implemented for FtpObserver interface.
	// To monitor download progress.
	public void byteRead(int bytes) {
		num_of_bytes += bytes;
		System.out.println(num_of_bytes + " of bytes read already.");
	}

	// Needed to implements by FtpObserver interface.
	public void byteWrite(int bytes) {
	}

	// Main
	public static void main(String[] args) {
		FtpServerMain example = new FtpServerMain();
		example.connect();
		example.listDirectory();
		example.getFile();
		example.close();
	}
}
